package com.binguo.api.schedule;

import com.binguo.api.baidu.BaiduRecUtil;
import com.binguo.api.service.RedisLockService;
import com.binguo.api.service.YizhifuService;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.service.CustomerService;
import com.binguo.service.DeviceMsgService;
import com.binguo.service.NewDiscountService;
import com.binguo.thirdPay.hzShiMing.HZShiMingService;
import com.binguo.thirdPay.zy.ZytkService;
import com.binguo.yprecapi.YpRecService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleService {

    private static Logger logger = LoggerFactory.getLogger(ScheduleService.class);
    @Autowired
    private ShopZyParamRepository shopZyParamRepository;

    @Autowired
    ZytkService zytkService;

    @Autowired
    YizhifuService yizhifuService;

    @Resource
    RedisLockService redisLockService;

    @Autowired
    HZShiMingService hzShiMingService;

    @Autowired
    NewDiscountService discountService;

    @Autowired
    CustomerService customerService;

    @Autowired
    YpRecService ypRecService;

    @Autowired
    DeviceMsgTemporaryRepository deviceMsgTemporaryRepository;

    @Resource
    DeviceMsgTemporaryMapper deviceMsgTemporaryMapper;

    @Autowired
    DeviceMsgService deviceMsgService;
    @Resource
    ShopZyOrderMapper shopZyOrderMapper;
    @Autowired
    ShopRepository shopRepository;
    @Autowired
    BranchRepository branchRepository;
    @Autowired
    ProductCategoryRepository productCategoryRepository;
    @Autowired
    PayCardRepository payCardRepository;
    @Resource
    PayCardMapper payCardMapper;

    @Resource
    LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;


    @Resource
    ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;
    @Resource
    CashierDeskMapper cashierDeskMapper;


    @Resource
    LogProductImgFromUserMapper logProductImgFromUserMapper;
    @Resource
    ProductSubMapper productSubMapper;
    @Resource
    ProductMapper productMapper;

//    @Scheduled(cron="* * * * * *") //测试每秒执行
//    @Scheduled(cron="0 0 0/1 * * ?") //每天零晨执行
//    public void test() throws Exception {
//        String key = "ZhengYuanUpdate";
//
//        String uuid = UUID.randomUUID().toString();
//        boolean lock = redisLockService.setLock(key, 10000, uuid);
//        if (lock) {
//            System.out.println("update shop zy param");
//            update();
//            System.out.println("schedule");
//        }
//    }

    @Autowired
    BaiduRecUtil baiduRecUtil;

    @Resource
    LogProductImgMapper logProductImgMapper;

    @Resource
    ShopHoursConfigMapper shopHoursConfigMapper;

    @Resource
    ShopProductVersionMapper shopProductVersionMapper;

    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");


    @Scheduled(cron="0/30 * * * * ?") //每秒更新
    public void shopHouConfigUpdate() throws Exception {
        logger.info("====shopHouConfigUpdate===");
        String key = "shopHouConfigUpdate";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            Map<Integer, ShopProductVersion> map = null;
            List<ShopProductVersion> shopProductVersionList = shopProductVersionMapper.selectAll();
            if (shopProductVersionList != null && shopProductVersionList.size() > 0) {
                map = shopProductVersionList.stream().collect(Collectors.toMap(ShopProductVersion::getShopId, p -> p));
            }

            Condition shopHourCondition = new Condition(ShopHoursConfig.class);
            shopHourCondition.or().andEqualTo("hourType", 2);
            List<ShopHoursConfig> shopHoursConfigList = shopHoursConfigMapper.selectByCondition(shopHourCondition);

            if (shopHoursConfigList != null && shopHoursConfigList.size() > 0) {
                Date now = new Date();

                try {
                    now = formatter.parse(formatter.format(now));



                } catch (ParseException e) {
                    e.printStackTrace();
                }
                for (ShopHoursConfig shopHoursConfig : shopHoursConfigList) {

                    if (now.after(shopHoursConfig.getEndTime())) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(shopHoursConfig.getEndTime());
                        calendar.add(Calendar.SECOND, 30);

                        if (now.before(calendar.getTime())) {
                            ShopProductVersion shopProductVersion = map.get(shopHoursConfig.getShopId());
                            boolean forUpdate = true;
                            if (shopProductVersion == null) {
                                shopProductVersion = new ShopProductVersion();
                                shopProductVersion.setProductVersion(2);
                                shopProductVersion.setShopId(shopHoursConfig.getShopId());
                                shopProductVersion.setCreateTime(new Date());
                                shopProductVersion.setBranchId(shopHoursConfig.getBranchId());
                                shopProductVersion.setUpdateTime(new Date());
                                forUpdate = false;
                            }
                            shopProductVersion.setProductVersion(shopProductVersion.getProductVersion() + 1);
                            shopProductVersion.setUpdateTime(new Date());
                            if (forUpdate) {
                                shopProductVersionMapper.updateByPrimaryKeySelective(shopProductVersion);
                            }else {
                                shopProductVersionMapper.insertSelective(shopProductVersion);
                            }
                        }

                    }

                    if (now.after(shopHoursConfig.getStartTime()) && shopHoursConfig.getEndTime().after(now)) {
                        ShopProductVersion shopProductVersion = map.get(shopHoursConfig.getShopId());

                        boolean forUpdate = true;
                        if (shopProductVersion == null) {
                            shopProductVersion = new ShopProductVersion();
                            shopProductVersion.setProductVersion(2);
                            shopProductVersion.setCreateTime(new Date());
                            shopProductVersion.setShopId(shopHoursConfig.getShopId());
                            shopProductVersion.setBranchId(shopHoursConfig.getBranchId());
                            shopProductVersion.setUpdateTime(new Date());
                            forUpdate = false;
                        }
                        Date updateTime = shopProductVersion.getUpdateTime();
                        try {
                            updateTime = formatter.parse(formatter.format(updateTime));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (updateTime.after(shopHoursConfig.getStartTime()) && shopHoursConfig.getEndTime().after(updateTime)) {
                            continue;
                        }else {
                            shopProductVersion.setProductVersion(shopProductVersion.getProductVersion() + 1);
                            shopProductVersion.setUpdateTime(new Date());
                            if (forUpdate) {
                                shopProductVersionMapper.updateByPrimaryKeySelective(shopProductVersion);
                            }else {
                                shopProductVersionMapper.insertSelective(shopProductVersion);
                            }
                        }
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 30 * * * ?") //每天2:00执行
    public void delShopBaiduUrlImg() throws Exception {
        logger.info("====delShopBaiduUrlImg===");
        String key = "delShopBaiduUrlImg";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 30000, uuid);
        if (lock) {
            Condition condition = new Condition(LogShopBaiduImgDel.class);
            condition.or().andEqualTo("status", 0);
            List<LogShopBaiduImgDel> imgDelList = logShopBaiduImgDelMapper.selectByCondition(condition);
            if (imgDelList != null && imgDelList.size() > 0) {
                for (LogShopBaiduImgDel logShopBaiduImgDel : imgDelList) {

                    if (logShopBaiduImgDel.getImgType() == null || logShopBaiduImgDel.getImgType().intValue() == 2) {
                        LogProductImgFromUser p = logProductImgFromUserMapper.selectByPrimaryKey(logShopBaiduImgDel.getLogId());
                        if (p != null) {
                            boolean deleted = false;
                            if (p.getSubDb() == null || p.getSubDb() == 0) {
                                deleted = baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                            }else{
                                deleted = baiduRecUtil.delImgCurList(p.getContSign(), p.getShopId(), p.getBranchId(), p.getBaiduAppId());
//                                deleted = baiduRecUtil.delImgCur(p.getContSign(), p.getShopId(), p.getBranchId());
                            }
                            if (deleted) {
                                LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                                temp.setId(logShopBaiduImgDel.getId());
                                temp.setStatus(1);

                                logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                            }else {
                                break;
                            }
                        }else {
                            LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                            temp.setId(logShopBaiduImgDel.getId());
                            temp.setStatus(1);

                            logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                        }
                    }else {
                        LogProductImg p = logProductImgMapper.selectByPrimaryKey(logShopBaiduImgDel.getLogId());
                        if (p != null) {
                            if(baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                                LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                                temp.setStatus(1);
                                temp.setId(logShopBaiduImgDel.getId());

                                logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                            }
                        }else {
                            LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                            temp.setId(logShopBaiduImgDel.getId());
                            temp.setStatus(1);

                            logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                        }
                    }

                }
            }
        }
    }

//    @Scheduled(cron="0 * * * * ?") //每天3:00执行
//    @Scheduled(cron="0 * * * * ?") //每天3:00执行
    @Scheduled(cron="0 0 4 * * ?") //每天3:00执行
    public void eraseShopBaiduUrlCur2() throws Exception {
        eraseShopBaiduUrlCur();
    }


    @Scheduled(cron="0 0 3 * * ?") //每天3:00执行
    public void eraseShopBaiduUrlCur() throws Exception {

        String key = "eraseShopBaiduUrlCurNew";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            Condition shopCondition = new Condition(Shop.class);
            shopCondition.or().andEqualTo("productRecType", 4);
            List<Shop> shopList = shopRepository.findByCondition(shopCondition);

            for (Shop shop : shopList) {
                Condition productSubCondition = new Condition(ProductSub.class);
                productSubCondition.or().andEqualTo("shopId", shop.getId());

                List<ProductSub> productSubList = productSubMapper.selectByCondition(productSubCondition);

                if (productSubList != null && productSubList.size() > 0) {
                    ypRecService.delAllImg(productSubList.get(0).getBranchId(), DataLoadService.recip);
                    productSubMapper.deleteByCondition(productSubCondition);
                }
            }

            Condition condition = new Condition(ShopBaiduUrlCur.class);

            condition.or().andEqualTo("urlType", 2)
                    .andEqualTo("used", 1)
            ;
            List<ShopBaiduUrlCur> shopBaiduUrlCurList = shopBaiduUrlCurMapper.selectByCondition(condition);

            if (shopBaiduUrlCurList != null && shopBaiduUrlCurList.size() > 0) {
                for (ShopBaiduUrlCur shopBaiduUrlCur : shopBaiduUrlCurList) {
                    Integer shopId = shopBaiduUrlCur.getShopId();

                    Condition logProductImgFromUserConditon = new Condition(LogProductImgFromUser.class);
                    logProductImgFromUserConditon.or().andEqualTo("shopId", shopId)
                        .andEqualTo("subDb", 1)
                        .andEqualTo("baiduDeleted", 0)
                    ;

                    List<LogProductImgFromUser> logProductImgFromUserList =
                            logProductImgFromUserMapper.selectByCondition(logProductImgFromUserConditon);

                    if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
                        for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                            if (logProductImgFromUser.getBranchId() == null) {
                                Product product = productMapper.selectByPrimaryKey(logProductImgFromUser.getProductId());
                                if (product == null) {
                                    continue;
                                }
                                logProductImgFromUser.setBranchId(product.getStoreid());
                            }
                            boolean deleted = baiduRecUtil.delImgCurList(logProductImgFromUser.getContSign(), shopId, logProductImgFromUser.getBranchId(), logProductImgFromUser.getBaiduAppId());
//                            boolean deleted = baiduRecUtil.delImgCur(logProductImgFromUser.getContSign(), shopId, logProductImgFromUser.getBranchId());
                            if (deleted) {
                                LogProductImgFromUser temp = new LogProductImgFromUser();
                                temp.setId(logProductImgFromUser.getId());
                                temp.setBaiduDeleted(1);
                                logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                            }
                        }
                    }

                    Condition productSubCondition = new Condition(ProductSub.class);
                    productSubCondition.or().andEqualTo("shopId", shopId);

                    productSubMapper.deleteByCondition(productSubCondition);
                }
            }
        }
    }

    @Scheduled(cron="0 0 2 * * ?") //每天2:00执行
    public void yiZhiFuSendTXT() throws Exception {
        String key = "yiZhiFuSendTXT";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);
            Date time = cal.getTime();
            String sqlDate = new SimpleDateFormat("yyyy-MM-dd").format(time);
            yizhifuService.createDayTXT(sqlDate);
        }
    }

    @Scheduled(cron="0 0 1 * * ?") //每天1:00执行
    public void deleteDiscountOrderByDay(){
        String key = "deleteDiscountOrderByDay";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            discountService.deleteAllDiscountOrder();
        }
    }

    @Scheduled(cron="0 30 * * * ?") //每天15:00执行
//    @Scheduled(cron="0 0/30 * * * ?") //每天15:00执行
    public void updateZyBanalanceTwo() throws Exception {
         updateZyBanlance();
    }


    /*@Scheduled(cron="0 * * * * ?") //每天15:00执行
    public void updateZyBanalanceTwoa() throws Exception {
         updateZyBanlance();
    }*/

    /*@Scheduled(cron="0 0 16 * * ?") //每天16:00执行
    public void updateZyBanlanceTwo() throws Exception {
        updateZyBanlance();
    }*/

//    @Scheduled(cron="0 * * * * ?") //每天11:00执行
    @Scheduled(cron="0 0 11 * * ?") //每天11:00执行
    public void updateZyBanlance() throws Exception {
        String key = "updateZyBanlance";


        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            logger.info("begin updateZyBanlance===================");

            Condition shopCondition = new Condition(Shop.class);
            shopCondition.or().andEqualTo("payType", 7);

            List<Shop> shopList = shopRepository.findByCondition(shopCondition);

            if (shopList != null && shopList.size() > 0) {
                for (Shop shop : shopList) {
                    ShopZyParam shopZyParam = shopZyParamRepository.findBy("shopId", shop.getId());
                    if (shopZyParam != null && shopZyParam.getNetState() != null && shopZyParam.getNetState().intValue() == 1) {

                        Condition payCardCondition = new Condition(PayCard.class);
                        payCardCondition.or().andEqualTo("shopid", shop.getId())
                                .andEqualTo("cardtype", 2)
                        ;

                        List<PayCard> payCardList = payCardRepository.findByCondition(payCardCondition);

                        if (payCardList != null && payCardList.size() > 0) {
                            for (PayCard payCard : payCardList) {
                                logger.info("paycard begin update, id:{}, name:{}", payCard.getId(), payCard.getName());

                                String balance = zytkService.GetAccDBMoney(payCard.getCardno(), shop.getId(), "1");

                                if (balance != null) {
                                    PayCard temp = new PayCard();
                                    temp.setId(payCard.getId());
                                    temp.setYktAccountbalance(Long.valueOf(balance));

                                    payCardMapper.updateByPrimaryKeySelective(temp);
                                    logger.info("paycard end update, id:{}, name:{}", payCard.getId(), payCard.getName());
                                }

                            }
                        }
                    }else {
                        if (shopZyParam != null && shop != null) {
                            logger.info("shopId:{}, netstate:{}", shop.getId(), shopZyParam.getNetState());
                        }
                    }
                }
            }


        }
    }

    @Scheduled(cron = "0 30 * * * ?")
    public void updateDeviceMsg() throws Exception{
        System.out.printf("begin updateDeviceMsg====");
        String key = "updateDeviceMsg";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, -60);//查找60分钟内用户未提交姓名和分组信息的记录
            Condition condition = new Condition(DeviceMsgTemporary.class);
            condition.or().andEqualTo("allowStatus", "1")
                    .andEqualTo("status", "0")
                .andGreaterThan("createTime", calendar.getTime())
            ;
            List<DeviceMsgTemporary> deviceMsgTemporaryList =
                    deviceMsgTemporaryRepository.findByCondition(condition);

            if (deviceMsgTemporaryList != null && deviceMsgTemporaryList.size() > 0) {
                List<Integer> idList = new ArrayList<>();
                for (DeviceMsgTemporary deviceMsgTemporary : deviceMsgTemporaryList) {
                    if(deviceMsgService.addDeviceMsg(deviceMsgTemporary.getShopId(), deviceMsgTemporary.getCustomerId(),
                            deviceMsgTemporary.getCustomerName(), deviceMsgTemporary.getFaceUrl(),
                            "1", deviceMsgTemporary.getFaceId())){
                        idList.add(deviceMsgTemporary.getId());
                    }
                }

                if (idList.size() > 0) {
                    DeviceMsgTemporary temporary = new DeviceMsgTemporary();
                    temporary.setStatus(1);

                    Condition updateCondition = new Condition(DeviceMsgTemporary.class);
                    updateCondition.or().andIn("id", idList);
                    deviceMsgTemporaryMapper.updateByConditionSelective(temporary, updateCondition);
                }
            }
            hzShiMingService.queryRefundOrder();
        }
    }

    @Scheduled(cron = "0 30 * * * ?")
    public void updateShopZyOrder() throws Exception{
        System.out.printf("begin updateShopZyOrder====");
        String key = "updateShopZyOrder";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            List<ShopZyParam> shopZyParamList = shopZyParamRepository.findAll();
            List<Integer> shopIdList = new ArrayList<>();
            if (shopZyParamList != null && shopZyParamList.size() > 0) {
                for (ShopZyParam shopZyParam : shopZyParamList) {
                    if (shopZyParam.getNetState() != null && shopZyParam.getNetState().intValue() == 1) {
                        shopIdList.add(shopZyParam.getShopId());
                    }
                }
            }

            if (shopIdList.size() == 0) {
                return;
            }

            Condition condition = new Condition(ShopZyOrder.class);
            condition.or().andEqualTo("syncStatus", 0)
                .andIn("shopId", shopIdList)
            ;
            List<ShopZyOrder> shopZyOrderList = shopZyOrderMapper.selectByCondition(condition);

            if (shopZyOrderList != null && shopZyOrderList.size() > 0) {
                for (ShopZyOrder shopZyOrder : shopZyOrderList) {
                    ShopZyOrder temp = new ShopZyOrder();
                    temp.setId(shopZyOrder.getId());
                    temp.setSyncStatus(1);

                    Condition updateCondition = new Condition(ShopZyOrder.class);
                    updateCondition.or().andEqualTo("syncStatus", 0)
                        .andEqualTo("id", shopZyOrder.getId())
                    ;
                    int count = shopZyOrderMapper.updateByConditionSelective(temp, updateCondition);

                    if (count == 1) {
                        String result = null;
                        if (StringUtils.hasText(shopZyOrder.getStatnum())) {
                            result = zytkService.PaymentAWithStatnum(shopZyOrder.getCardId(),
                                    shopZyOrder.getPrice().toString(), shopZyOrder.getShopId(), shopZyOrder.getStatnum());
                        }else{
                            result = zytkService.PaymentA(shopZyOrder.getCardId(),
                                    shopZyOrder.getPrice().toString(), shopZyOrder.getShopId());
                        }

                        if (result.equals("failed")) {
                            temp.setSyncStatus(0);
                            shopZyOrderMapper.updateByPrimaryKeySelective(temp);
                        }
                    }

                }
            }


        }
    }


    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateShopZyParamNetStatus() throws Exception{
        String key = "updateShopZyParamNetStatus2";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            System.out.println("begin updateShopZyParamNetStatus====");
            update();
            System.out.println("end updateShopZyParamNetStatus====");
        }
    }

    @Scheduled(cron = "0 30 * * * ?")
    public void queryShiMingOrder() throws Exception{
        String key = "queryShiMingOrder";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 100000, uuid);
        if (lock) {
            hzShiMingService.queryPayOrder();
            hzShiMingService.queryRefundOrder();
        }
    }

    @Scheduled(cron = "0 30 * * * ?")
    public void correctData() throws Exception{
        String key = "correctShopData";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLockOrder(key, 100000, uuid);
        if (lock) {
            List<Shop> shopList = shopRepository.findAll();

            List<Branch> branchList = branchRepository.findAll();

            Map<Integer, List<Branch>> shopBranchListMap = new HashMap<>();
            for (Branch branch : branchList) {
                List<Branch> shopBranchList = shopBranchListMap.get(branch.getShopId());

                if (shopBranchList == null) {
                    shopBranchList = new ArrayList<>();
                }

                shopBranchList.add(branch);

                shopBranchListMap.put(branch.getShopId(), shopBranchList);
            }

            for (Shop shop : shopList) {
                List<Branch> shopBranchList = shopBranchListMap.get(shop.getId());

                Integer branchId = null;
                if (shopBranchList == null) {
                    branchId = addNewBranch(shop);
                }else {
                    if (shopBranchList.size() == 1) {
                        branchId = shopBranchList.get(0).getBranchId();
                    }
                }

                Condition productCondition = new Condition(Product.class);
                productCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("deleted", false);
                List<Product> productList = productMapper.selectByCondition(productCondition);

                if (productList != null && productList.size() > 0) {
                    boolean zidingyiProductExist = false;
                    for (Product product : productList) {
                        if (product.getStoreid() == null) {
                            if (branchId != null) {
                                Product temp = new Product();
                                temp.setId(product.getId());
                                temp.setStoreid(branchId);
                                productMapper.updateByPrimaryKeySelective(temp);
                            }
                        }

                        if ("-5".equals(product.getSearchcode())) {
                            zidingyiProductExist = true;
                        }
                    }

                    if (!zidingyiProductExist && branchId != null) {
                        addZidingyiProduct(shop, branchId);
                    }
                }

                if (branchId != null) {
                    Condition cashierDeskCondition = new Condition(CashierDesk.class);
                    cashierDeskCondition.or().andEqualTo("branchid", 0).andEqualTo("shopid", shop.getId());
                    List<CashierDesk> cashierDeskList = cashierDeskMapper.selectByCondition(cashierDeskCondition);

                    if (cashierDeskList != null && cashierDeskList.size() > 0) {
                        for (CashierDesk cashierDesk : cashierDeskList) {
                            CashierDesk temp = new CashierDesk();
                            temp.setId(cashierDesk.getId());
                            temp.setBranchid(branchId);

                            cashierDeskMapper.updateByPrimaryKeySelective(temp);
                        }
                    }
                }
            }


        }
    }

    //每个整点执行一次
    @Scheduled(cron = "30 0 0/1 * * ?")
    public void updateMonthRecharge(){
        String key = "updateMonthRecharge";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLockOrder(key, 10000, uuid);
        if (lock) {
            customerService.rechargeByMonthDay();
        }
    }


    private Integer addNewBranch(Shop shop){
        Branch branch = new Branch();
        branch.setShopId(shop.getId());
        branch.setBranchName(shop.getName());
        branch.setBranchPricetype(0);

        branchRepository.save(branch);

        return branch.getBranchId();
    }
    private void addZidingyiProduct(Shop shop, Integer branchId){
        Condition condition = new Condition(ProductCategory.class);
        condition.or().andEqualTo("shopid", shop.getId());
        List<ProductCategory> productCategoryList = productCategoryRepository.findByCondition(condition);
        Integer categoryId = null;
        if (productCategoryList != null && productCategoryList.size() > 0) {
            categoryId = productCategoryList.get(0).getId();
        }

        if (categoryId == null) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setType(new Byte("1"));
            productCategory.setShopid(shop.getId());
            productCategory.setName("全部");
            productCategory.setDeleted(false);
            productCategory.setParentid(0);
            productCategoryRepository.save(productCategory);

            categoryId = productCategory.getId();
        }
        Product product = new Product();
        product.setStoreid(branchId);
        product.setPrice(100l);
        product.setVipprice(100l);
        product.setName("自定义菜品");
        product.setProductType(1);
        product.setShopid(shop.getId());
        product.setStatus(new Byte("1"));
        product.setSearchcode("-5");
        product.setDeleted(false);
        product.setCreated(new Date());
        product.setUpdated(product.getCreated());
        product.setMinorcategoryid(categoryId);

        productMapper.insertSelective(product);

    }

    public void update() throws Exception {
        List<ShopZyParam> shopZyParamList =  shopZyParamRepository.findAll();
        for (ShopZyParam shopZyParam : shopZyParamList){
            System.out.println(shopZyParam.getZyUrl());
            try {
                Map<String, Object> result = zytkService.SignIn(shopZyParam.getZyUrl());

                if (result != null && result.get("Secret1").toString().length() > 2) {
                    System.out.println(result.get("Secret1").toString());
                    shopZyParam.setSecret1(result.get("Secret1").toString());
                    shopZyParam.setSecret2(result.get("Secret2").toString());
                    shopZyParam.setThirdType(result.get("thirdType").toString());
                    shopZyParam.setNetState(1);
                    shopZyParamRepository.update(shopZyParam);
                }
            } catch (Exception e) {
                System.out.println(e);
                shopZyParam.setNetState(0);
                shopZyParamRepository.update(shopZyParam);
            }

        }

    }
}
